<template>
  <!--开票审核-->
  <BasicModal :title="getTitle" @register="registerModal" destroyOnClose
              :showCancelBtn="false" :showOkBtn="false" :canFullscreen="false" :centered="true"
              :width="'95%'" :loading="loading"
              :bodyStyle="{height:'calc(100vh - 120px)', overflowY:'auto'}"
  >
    <div class="input" style="zoom: 1; padding:5px; min-width:1200px;" :style="{height:'calc(100vh - 150px)', overflowY:'auto'}">
      <table class="orderTable orderTableAlign" id="orderTable">
        <thead>
        <tr>
          <th colspan="14" align="left">
            <span class="fl w200 leading-30px">票据申请</span>
            <span class="float-right h-30px leading-30px">
              <a-button size="small" type="default" color="success" @click.prevent="businessDdzt('1')" :disabled="model.ddzt == 1" class="mr-2">完成</a-button>
              <a-button size="small" type="default" color="success" @click.prevent="businessDdzt('0')" :disabled="model.ddzt == 0" class="mr-2">取消</a-button>
              <a-button size="small" type="default" color="warning" @click.prevent="handleBusinessMod" class="mr-2">修改</a-button>
              <a-button size="small" type="default" color="error" @click.prevent="handleBusinessDel" class="mr-2">删除</a-button>
            </span>
          </th>
        </tr>
        </thead>
        <tbody>
        <!----开票审核-------------------->
        <tr class="h-25px leading-25px" v-if="model.sflx == '1'">
          <th>名称：</th>
          <td colspan="3"><div>{{model.dwmc}}</div></td>
          <th width="80">登记编号：</th>
          <td width="180"><div>{{model.orderId}}</div></td>
          <th width="80">已付款：</th>
          <td width="180"><div class="fwb tar green">{{model.fkje}}</div></td>
          <th width="80">已收款：</th>
          <td width="180"><div class="fwb tar red">{{model.skje}}</div></td>
        </tr>
        <!----回票审核-------------------->
        <tr class="h-25px leading-25px" v-else>
          <th>名称：</th>
          <td colspan="3"><div>{{model.dwmc}}</div></td>
          <th width="80">登记编号：</th>
          <td width="180"><div>{{model.orderId}}</div></td>
          <th width="80">已收款：</th>
          <td width="180"><div class="fwb tar red">{{model.skje}}</div></td>
          <th width="80">已付款：</th>
          <td width="180"><div class="fwb tar green">{{model.fkje}}</div></td>
        </tr>
        <!----开票审核-------------------->
        <tr class="h-25px leading-25px" v-if="model.sflx == '1'">
          <th width="80">状态：</th>
          <td width="180"><div>{{model.ddzt_zw}}</div></td>
          <th width="80">操作人：</th>
          <td width="180"><div>{{model.lrr}}</div></td>
          <th width="80">审核人：</th>
          <td width="180"><div>{{model.qrr}}</div></td>
          <th width="80">属性：</th>
          <td width="180"><div>{{model.sqlx_zw}}</div></td>
          <th width="80">已开票：</th>
          <td width="180"><div class="fwb tar red">{{model.fpsk}}</div></td>
        </tr>
        <!----回票审核-------------------->
        <tr class="h-25px leading-25px" v-else>
          <th width="80">状态：</th>
          <td width="180"><div>{{model.ddzt_zw}}</div></td>
          <th width="80">操作人：</th>
          <td width="180"><div>{{model.lrr}}</div></td>
          <th width="80">审核人：</th>
          <td width="180"><div>{{model.qrr}}</div></td>
          <th width="80">申请金额：</th>
          <td width="180"><div class="fwb tar red">{{model.sqje}}</div></td>
          <th width="80">已回票：</th>
          <td width="180"><div class="fwb tar green">{{model.fpfk}}</div></td>
        </tr>
        <tr class="h-25px leading-25px">
          <th width="80">类型：</th>
          <td width="180"><div id="_sflx_zw">{{model.sflx_zw}}</div></td>
          <th>操作日期：</th>
          <td><div id="_lrsj">{{model.lrsj}}</div></td>
          <th>审核日期：</th>
          <td><div id="_qrsj">{{model.qrsj}}</div></td>
          <th width="80">归属日期：</th>
          <td width="180">
            <a-month-picker
              v-model:value="model.invoiceDate"
              valueFormat="YYYY-MM"
              placeholder=""
              style="width: 110px"
            />
          </td>
          <th width="80">票差：</th>
          <td width="180"><div id="_fpce" class="fwb tar blue">{{model.fpce}}</div></td>
        </tr>
        </tbody>
      </table>

      <table class="orderTable orderTableAlign" id="companyTable" v-if="model.sflx == '1'">
        <thead>
        <tr>
          <th colspan="14" align="left">
            <span class="fl w200">开票信息</span>
          </th>
        </tr>
        </thead>
        <tbody>
        <tr class="h-25px leading-25px">
          <th width="80">单位名称：</th>
          <td width="180"><div id="_companyName">{{model.companyName}}</div></td>
          <th width="80">纳税人号：</th>
          <td width="180"><div id="_companyNumber">{{model.companyNumber}}</div></td>
          <th width="80">地址电话：</th>
          <td width="180"><div id="_companyAddress">{{model.companyAddress}}</div></td>
          <th width="80">交接人：</th>
          <td width="180"><div id="_lxr">{{model.lxr}}</div></td>
          <th width="80">邮箱：</th>
          <td width="180"><div id="_meil">{{model.meil}}</div></td>
        </tr>
        <tr class="h-25px leading-25px">
          <th width="80">开户行：</th>
          <td width="180"><div id="_companyBankname">{{model.companyBankname}}</div></td>
          <th width="80">账号：</th>
          <td width="180"><div id="_companyBankno">{{model.companyBankno}}</div></td>
          <th width="80">备注：</th>
          <td width="180" colspan="3"><div id="_comments">{{model.comments}}</div></td>
          <th>申请金额：</th>
          <td><div id="_sqje" class="fwb tar block">{{model.sqje}}</div></td>
        </tr>
        </tbody>
      </table>

      <div class="listtab1" id="con_menu_1" style="display: block;">
        <form id="bucForm" action="" method="post">
          <table class="orderTable" id="buctable">
            <thead>
            <tr class="h-30px leading-30px">
              <th colspan="11">
                <a href="#" @click.prevent="handleOpenAccountDel" :class="{'disableCss': invoiceFlowOption.btnDelDisabled}" class="float-right mr-10px font-600" hidefocus>撤消</a>
                <a href="#" @click.prevent="handleOpenAccountGrid" :class="{'disableCss': invoiceFlowOption.btnAddDisabled}" class="float-right mr-10px font-600" hidefocus>添加</a>
                收支项目
              </th> <!-- 自定义a.popup标签，bind弹出窗方法 -->
            </tr>
            </thead>
            <tbody>
            <tr class="listBg">
              <th width="20" class="check"><input type="checkbox" class="infoAllCheck" @change="flowAllCheck" :checked="invoiceFlowOption.checked" :disabled="invoiceFlowOption.disabled"/></th>
              <th width="70" class="tac">部门</th>
              <th width="110" class="tac">订单号</th>
              <th width="100" class="tac">银行</th>
              <th width="300">收付单位</th>
              <th width="100" class="tar">已收款</th>
              <th width="100" class="tar">已付款</th>
              <th width="90" class="tac">收付日期</th>
              <th class="tal">备注</th>
              <th width="90" class="tac">操作日期</th>
              <th width="80" class="tac">操作人</th>
            </tr>
            <tr v-for="(list, index) in invoiceFlows.optionList" :key="index" :class="(index%2==0) ? 'listBg' : 'cor'">
              <td><input type="checkbox" name="ids" :id="'acc' + list.id" @change="flowOneCheck(index)" :checked="invoiceFlowOption.nid.indexOf(list.id) > -1" :disabled="invoiceFlowOption.disabled || list.stat === '3'"/></td>
              <td>{{list.ddlx_zw}}</td>
              <td>{{list.orderId}}</td>
              <td>{{list.djm}}</td>
              <td class="text-left">{{list.dwmc}}</td>
              <td class="text-right text-red-600">{{list.skje}}</td>
              <td class="text-right text-green-600">{{list.fkje}}</td>
              <td>{{list.sfsj}}</td>
              <td class="text-left">{{list.afbz}}</td>
              <td>{{list.lrsj}}</td>
              <td>{{list.lrr}}</td>
            </tr>
            </tbody>
            <tfoot>
            <tr>
              <td class="tips">&nbsp;</td>
              <td class="tips">小计</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td class="text-right font-600 text-red-500">{{invoiceFlows.sumSkje}}</td>
              <td class="text-right font-600 text-green-500">{{invoiceFlows.sumFkje}}</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
              <td>&nbsp;</td>
            </tr>
            </tfoot>
          </table>
        </form>
      </div>

      <div class="listtab1" id="con_menu_2" >
        <table class="orderTable" id="acctable">
          <thead>
          <tr>
            <th colspan="8">
              <a href="#" @click.prevent="handleInvoiceInfoDel" :class="{'disableCss': invoiceInfoOption.btnDelDisabled}" class="float-right mr-10px font-600" hidefocus>删除</a>
              <a href="#" @click.prevent="handleInvoiceInfoEdt" :class="{'disableCss': invoiceInfoOption.btnEdtDisabled}" class="float-right mr-10px font-600" hidefocus>编辑</a>
              <a href="#" @click.prevent="handleInvoiceInfoEdt" :class="{'disableCss': invoiceInfoOption.btnAddDisabled}" class="float-right mr-10px font-600" hidefocus>添加</a>
              票据信息
            </th>
          </tr>
          </thead>
          <tbody>
          <tr class="listBg">
            <th width="20" class="check"><input type="checkbox" class="infoAllCheck" @change="infoAllCheck" :checked="invoiceInfoOption.checked" :disabled="invoiceInfoOption.disabled"/></th>
            <th width="90" class="tac">{{model.sflx_zw}}日期</th>
            <th width="120" class="tar">{{model.sflx_zw}}金额</th>
            <th width="90" class="tar">张数</th>
            <th width="200" class="tal">内容</th>
            <th>备注</th>
            <th width="100" class="tac">操作时间</th>
            <th width="80" class="tac">操作人</th>
          </tr>
          </tbody>
          <tbody v-for="(list, index) in invoiceInfos.optionList" :key="index">
          <tr>
            <td><input type="checkbox" name="ids" :id="'info' + list.id" @change="infoOneCheck(index)" :checked="invoiceInfoOption.nid.indexOf(list.id) > -1" :disabled="invoiceInfoOption.disabled"/></td>
            <td>{{list.invoiceDate}}</td>
            <td class="text-right">{{list.sflx == "1" ? list.skje : list.fkje}}</td>
            <td class="text-right">{{list.number}}</td>
            <td class="text-left">{{list.content}}</td>
            <td class="text-left">{{list.bz}}</td>
            <td>{{list.lrsj}}</td>
            <td>{{list.lrr}}</td>
          </tr>
          </tbody>
          <tfoot>
          <tr>
            <td>&nbsp;</td>
            <td class="tips">小计</td>
            <td class="tips tar fwb red" id="info_sumskje">{{invoiceInfos.sumSkje}}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </BasicModal>

  <OpenAccountGird @register="registerOpenAccountGird" @success="handleSuccess" ></OpenAccountGird>
  <OpenInvoiceInfo @register="registerOpenInvoiceInfo" @success="handleSuccess" ></OpenInvoiceInfo>
  <BackInvoiceInfo @register="registerBackInvoiceInfo" @success="handleSuccess" ></BackInvoiceInfo>
</template>

<script lang="ts" setup>
import "/@/design/order.css";
import { ref, computed, unref, reactive, watch } from "vue";
import { BasicModal, useModal, useModalInner } from "/@/components/Modal";
import {
  invoiceOrderById,
  invoiceFlowList,
  invoiceInfoList,
  invoiceAccountDel,
  invoiceOrderUpdate, invoiceOrderDelete, invoiceInfoDel, ajaxBusinessStat
} from "../types/invoice.api";
import { useMessage } from "/@/hooks/web/useMessage";
import OpenAccountGird from "./openAccountGird.vue";
import OpenInvoiceInfo from "./openInvoiceInfo.vue";
import BackInvoiceInfo from "./backInvoiceInfo.vue";

const { createMessage: $message } = useMessage();
const isUpdate = ref(true);
const loading  = ref(false);
const emit = defineEmits(['success', 'register']);

let $businessId = ref('');
let sflx = ref('');
//表单modal
let model = reactive<any>({})
let invoiceFlows = reactive<any>({})
let invoiceInfos = reactive<any>({})
const getTitle = computed(() => (sflx.value == '1' ? '开票审核管理' : '回票审核管理'));
//表单赋值
const [registerModal, { closeModal }] = useModalInner(async (data) => {
  //表单赋值
  init(data);
});

//TODO 初始化--加载数据------------------------------------
function init(data) {
  if (data.id) {
    $businessId.value = data.id;
  }
  sflx.value = data.sflx; //标题
  handleSuccess();
}

/**
 * 开票申请信息
 */
async function orderTable() {
  var params = { businessId: $businessId.value };//查询条件
  await invoiceOrderById(params).then((res) => {
    try {
      if (res.success != true) {
        $message.warning("orderTable：" + res.message);
        return false;
      }
      let result = res.result;
      //标题
      sflx.value = result.sflx;
      //1、业务数据 - 初始化
      Object.assign(model, result);
    } catch (e) {
      alert(e);
      return false;
    }
  }).finally(() => {

  });
}

/**
 * 加载收付业务信息
 */
async function invoiceFlowTable() {
  let params = { businessId: $businessId.value };
  await invoiceFlowList(params).then((res) => {
    if (res.success != true) {
      $message.warning("invoiceFlowTable：" + res.message);
      return false;
    }
    let result = res.result;
    //1、业务数据 - 初始化
    Object.assign(invoiceFlows, result);
  })
}

/**
 * 加载发票信息
 */
async function invoiceInfoTable() {
  let params = { businessId: $businessId.value };
  await invoiceInfoList(params).then((res) => {
    if (res.success != true) {
      $message.warning(res.message);
      return false;
    }
    let result = res.result;
    //1、业务数据 - 初始化
    Object.assign(invoiceInfos, result);
  })
}
//TODO 初始化--加载数据------------------------------------

//票据申请 - 修改
function handleBusinessMod() {
  var invoiceDate = model.invoiceDate;
  if (!invoiceDate) {
    $message.warning("操作失败，归属日期无效！");
    return;
  }
  let param = { "id": $businessId.value, "invoiceDate" : invoiceDate};
  loading.value = true;
  invoiceOrderUpdate(param).then((res) => {
    if (res.success == true) {
      $message.success(res.message);
      orderTable();
      //refreshOrderButton();
      //isReload.value = true; //变量在 curdtools.js 里
    } else {
      $message.error(res.message);
    }
  }).finally(() => {
    loading.value = false;
  });
}

//票据申请 - 删除
function handleBusinessDel() {
  invoiceOrderDelete({ id: unref($businessId) }, businessDelAfter)
}

function businessDelAfter() {
  closeModal();
  emit("success");
  $message.success("操作成功！")
}

//TODO 收支项目------------------------------------------------------------------------------
/**
 * 收支项目 - 列表 - 添加
 * 弹出订单收支明细列表
 */
const [registerOpenAccountGird, { openModal: openAccountGridModal }] = useModal();
function handleOpenAccountGrid() {
  //invoiceListController.do?list
  let type = model.sflx == '1' ? 'open':'back';
  let params = {
    type: type,
    businessId: $businessId.value
  }
  //console.info("params@@@", params)
  openAccountGridModal(true, params);
}

//收支项目 - 列表 - 勾选数组
const invoiceFlowOption = reactive<any>({
  checked: false,
  nid: [],
  disabled: false,
});

// 全选
function flowAllCheck() {
  let me = invoiceFlowOption;
  me.checked = !me.checked;
  if (me.checked == true && model.ddzt == 0) {
    invoiceFlows.optionList.forEach((s) => {
      if (me.nid.indexOf(s.id) == -1 && s.stat !== '3') {
        me.nid.push(s.id);
      }
    });
    me.btnDelDisabled = false; //撤消
    me.btnAddDisabled = true;  //添加
  } else {
    me.nid = [];//清空数据
    me.btnDelDisabled = true;  //撤消
    me.btnAddDisabled = false; //添加
  }
}

//收支项目 - 列表 - 勾选操作
function flowOneCheck(index) {
  var list = invoiceFlows.optionList;
  var $id  = list[index].id;
  //勾选赋值
  var me  = invoiceFlowOption;
  var idx = me.nid.indexOf($id);
  if (idx !== -1) {
    me.nid.splice(idx, 1);
  } else {
    me.nid.push($id);
  }

  //勾选的数量等于列表的数量
  if (me.nid.length == invoiceFlows.optionList.length) {
    me.checked = true;
  }

  //勾选一个时才可编辑
  if (me.nid.length > 0) {
    me.btnDelDisabled = false;
    me.btnAddDisabled = true;
  } else {
    me.btnDelDisabled = true;
    me.btnAddDisabled = false;
    me.checked = false;
  }
}

//收支项目 - 删除
function handleOpenAccountDel() {
  let me = invoiceFlowOption
  if (me.nid.length <= 0) {
    $message.warning('请选择删除的记录！')
    return
  }
  let params = { ids: me.nid.join(','), businessId: unref($businessId) };
  invoiceAccountDel(params, handleSuccess)
}

//TODO 票据信息------------------------------------------------------------------------------
const [registerOpenInvoiceInfo, { openModal: openInvoiceInfoModal }] = useModal();
const [registerBackInvoiceInfo, { openModal: backInvoiceInfoModal }] = useModal();
//票据信息 - 列表 - 添加
function handleInvoiceInfoAdd() {
  let type = model.sflx == '1' ? 'open':'back';
  let params = {
    businessId: $businessId.value,
    isUpdate: false,
    type: type,
  }
  if (type == 'open') {
    openInvoiceInfoModal(true, params);
  } else {
    backInvoiceInfoModal(true, params);
  }
}

//票据信息 - 列表 - 勾选数组
const invoiceInfoOption = reactive<any>({
  checked: false,
  nid: [],
  disabled: false,
});

//票据信息 - 全选
function infoAllCheck() {
  let me = invoiceInfoOption;
  me.checked = !me.checked;
  if (me.checked == true && model.ddzt == 0) {
    invoiceInfos.optionList.forEach((s) => {
      if (me.nid.indexOf(s.id) == -1 && s.stat !== '3') {
        me.nid.push(s.id);
      }
    });
    if (me.nid.length == 1) {
      me.btnEdtDisabled = false;
    } else {
      me.btnEdtDisabled = true;
    }
    me.btnDelDisabled = false;  //删除
    me.btnAddDisabled = true;   //添加
  } else {
    me.nid = [];//清空数据
    me.btnDelDisabled = true;
    me.btnEdtDisabled = true;
    me.btnAddDisabled = false;  //添加
  }
}

//票据信息 - 列表 - 勾选操作
function infoOneCheck(index) {
  var list = invoiceInfos.optionList;
  var $id  = list[index].id;
  //勾选赋值
  var me  = invoiceInfoOption;
  var idx = me.nid.indexOf($id);
  if (idx !== -1) {
    me.nid.splice(idx, 1);
  } else {
    me.nid.push($id);
  }

  //勾选的数量等于列表的数量
  if (me.nid.length == invoiceInfos.optionList.length) {
    me.checked = true;
  }

  //勾选一个时才可编辑
  if (me.nid.length == 0) {
    me.btnAddDisabled = false;
  } else if (me.nid.length == 1) {
    me.btnEdtDisabled = false;
    me.btnAddDisabled = true;
  } else {
    me.btnEdtDisabled = true;
    me.btnAddDisabled = true;
  }
  me.btnDelDisabled = false;

  console.info("infoOneCheck@@@@", me)
}

function handleInvoiceInfoEdt() {
  let type = model.sflx == '1' ? 'open':'back';
  let record = { id: null, businessId: $businessId.value, type: type };
  let isUpdate = false
  if (invoiceInfoOption.nid.length == 0) {
    record.id = null;
    isUpdate = false;
  } else if (invoiceInfoOption.nid.length == 1) {
    record.id = invoiceInfoOption.nid[0];
    isUpdate = true;
    if (!record.id) {
      $message.warning("编辑操作，请先选择数据！");
      return
    }
  } else if (invoiceInfoOption.nid.length > 1) {
    $message.warning("编辑操作，一次只能选择一条记录！");
    return;
  }
  //检查订单编号
  if (!$businessId.value) {
    $message.warning("订单编号不能为空！");
    return;
  }

  if (type == 'open') {
    openInvoiceInfoModal(true, {record, isUpdate});
  } else {
    backInvoiceInfoModal(true, {record, isUpdate});
  }
}

function handleInvoiceInfoDel() {
  let me = invoiceInfoOption
  console.info(me);
  if (me.nid.length <= 0) {
    $message.warning('请选择删除的记录！')
    return
  }
  let params = { ids: me.nid.join(','), businessId: unref($businessId) };
  invoiceInfoDel(params, handleSuccess)
}

/**
 * 初始化按钮--------------------------------------------------------
 * 1、收支明细 - 添加 - 亮
 * 2、收支明细 - 撤销 - 灰
 * 1、发票信息 - 添加 - 亮
 * 2、发票信息 - 编辑 - 灰
 * 3、发票信息 - 编辑 - 灰
 */
function refreshOrderButton() {
  //收支明细全选，默认为不勾选
  invoiceFlowOption.nid = []
  invoiceFlowOption.checked = false;
  invoiceFlowOption.btnAddDisabled = false; //收支项目 - 添加
  invoiceFlowOption.btnDelDisabled = true;  //收支项目 - 撤销

  //票据信息全选，默认为不勾选
  invoiceInfoOption.nid = []
  invoiceInfoOption.checked = false;
  invoiceInfoOption.btnAddDisabled = false; //票据信息 - 添加
  invoiceInfoOption.btnEdtDisabled = true; //票据信息 - 编辑
  invoiceInfoOption.btnDelDisabled = true; //票据信息 - 删除
}

/**
 * 操作成功
 */
function handleSuccess() {
  orderTable();
  invoiceFlowTable();
  invoiceInfoTable();
  refreshOrderButton();
}


/**
 * 申请审核
 */
function businessDdzt(ddzt) {
  let data = { "id": model.id, "ddzt": ddzt };
  ajaxBusinessStat(data).then((res) => {
    if (res.success) {
      orderTable();
      refreshOrderButton();
      $message.success(res.message);
    } else {
      $message.error(res.message);
    }
  })
}
</script>

<style lang="less" scoped>

.formtable .inputxt {
  border: 1px solid #D7D7D7;
  border-radius: 3PX;
  padding: 7px 0 7px 5px;
  line-height: 14PX;
  font-size: 12px;
  display: inline-block;
  width: 200px;
}

.formtable .input_text:focus {
  border: 1px solid #06F;
  box-shadow: inset 0 1px 2px rgba(0, 102, 255, 0.3);
}

.formtable select {
  padding: 6px 2px;
  width: 155px;
}
.Validform_label {
  font-size: 12px;
  padding: 5px;
  white-space: nowrap;
}
.formtable {
  width: 100%;
  background-color: #ddd;
  align: right;
}
.formtable tr {
  background-color: #FAFAFA;
  align: right;
}
</style>
